'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken')

class LoginController extends Controller {
  async login() {
    const { ctx, app } = this;

    const { username, password } = ctx.request.body;

    const data = await app.mysql.get('userlist', { username, password })

    if (data) {
      ctx.body = {
        code: 1,
        token: jwt.sign(data.id, '1907A')
      }
    } else {
      ctx.status = 401

      ctx.body = {
        code: 0,
        msg: '用户名或者密码错误'
      }
    }
  }

  // 获取用户信息
  async getUserInfo() {
    const { ctx, app } = this;

    // 获取前端的请求头信息
    const { authorization } = ctx.request.headers;

    // 解密 authorization
    const id = jwt.verify(authorization, '1907A');

    try {
      // 通过id 换取用户信息
      const userInfo = await app.mysql.get('userlist', { id })

      // 解密成功  将用户信息返回给前端
      ctx.body = {
        code: 1,
        data: userInfo,
      }
    } catch (error) {
      // 解密失败 登录过期 让用户重新登录
      ctx.status = 401;

      ctx.body = {
        code: 0,
        msg: '登录已过期 请重新登录'
      }
    }


  }
}

module.exports = LoginController;
